package com.base.util;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.util.Log;

import java.util.HashMap;
import java.util.Map;

public class UsbHelper {
    private static final String TAG = "UsbHelper";
    public static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    private final Context mContext;
    private final Map<UsbDevice, Boolean> usbMap = new HashMap<>();
    private final UsbPermissionCallback callback;

    public UsbHelper(Context context, UsbPermissionCallback callback) {
        mContext = context;
        this.callback = callback;
        tryGetUsbPermission();
    }

    private void tryGetUsbPermission() {
        UsbManager mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);

        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        mContext.registerReceiver(mUsbPermissionActionReceiver, filter);

        PendingIntent mPermissionIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_PERMISSION), 0);

        //here do emulation to ask all connected usb device for permission
        for (final UsbDevice usbDevice : mUsbManager.getDeviceList().values()) {
            //add some conditional check if necessary
            //if(isWeCaredUsbDevice(usbDevice)){
            if (mUsbManager.hasPermission(usbDevice)) {
                usbMap.put(usbDevice, true);
                continue;
            }
            usbMap.put(usbDevice, false);
            mUsbManager.requestPermission(usbDevice, mPermissionIntent);
        }
    }

    private final BroadcastReceiver mUsbPermissionActionReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    boolean hasPermission = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false);
                    usbMap.put(usbDevice, hasPermission);
                    if (!hasPermission) {
                        //user choose NO for your previously popup window asking for grant perssion for this usb device
                        Log.e("onReceive", "onReceive: Permission denied for device" + usbDevice);
                    }

                    if (null != callback)
                        callback.onUsbCallback(hasPermission());
                }
            }
        }
    };

    public boolean hasPermission() {
        return usbMap.isEmpty() || !usbMap.containsValue(false);
    }

    public interface UsbPermissionCallback {
        void onUsbCallback(boolean success);
    }
}